<script lang="ts" setup>
import { reactive, ref } from "vue"
import { useRouter } from "vue-router"
import { useUserStore } from "@/store/modules/user"
import { type FormInstance, FormRules, ElMessage } from "element-plus"
import { User, Lock, Monitor, Ticket } from "@element-plus/icons-vue"
import { getLoginCodeApi } from "@/api/login"
import { type LoginRequestData } from "@/api/login/types/login"
import ThemeSwitch from "@/components/ThemeSwitch/index.vue"

const router = useRouter()
let { proxy } = getCurrentInstance() as any
let sendEmailRef = ref(false)
let emailMes = ref('发送验证码')

/** 登录表单元素的引用 */
const loginFormRef = ref<FormInstance | null>(null)
let activeName = ref('0')
/** 登录按钮 Loading */
const loading = ref(false)
/** 验证码图片 URL */
const codeUrl = ref("")
/** 登录表单数据 */
const loginFormData1: LoginRequestData = reactive({
  email: "",
  code: "",
})
const loginFormData: LoginRequestData = reactive({
  username: "",
  password: "",
})
/** 登录表单校验规则 */
const loginFormRules: FormRules = {
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 8, max: 16, message: "长度在 8 到 16 个字符", trigger: "blur" }
  ],
}
const loginFormRule1: FormRules = {
  email: [{ required: true, trigger: "blur", message: "请输入邮箱" }],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }]
}

const sendEmail = () => {
  let url = '/admin-api/wpes/user/send-mail-code'
  let params = {
    scene: '1',
    email: loginFormData1.email
  }
  proxy.$http.post(url, params, { headers: { "tenant-id": 1 } }).then(v => {
    let { code } = v.data
    if (code === 0) {
      emailMes.value = '发送成功'
      ElMessage.info('下次可在1分钟后再次发送')
      sendEmailRef.value = true
      setTimeout(() => {
        sendEmailRef.value = false;
        emailMes.value = '发送验证码';
      }, 60000);
    }
  })

}

/** 登录逻辑 */
const handleLogin = () => {
  if (activeName.value == '0') {
    loginFormRef.value?.validate((valid: boolean, fields) => {
      if (valid) {
        loading.value = true
        useUserStore()
          .login(loginFormData)
          .then((v: any) => {
            ElMessage.success('登录成功！')
            router.push("/modelTrain/index")
            /* 登录内部做的保存token 是保存到cookies   */
          })
          .catch((e) => {
            // createCode()
            console.log(e)
            loginFormData.password = ""
            // ElMessage.info(v.data.msg)
          })
          .finally(() => {
            loading.value = false
          })
      } else {
        console.error("表单校验不通过", fields)
      }
    })
  } else {
    let url = '/admin-api/wpes/user/mail-login'
    let params = {
      email: loginFormData1.email,
      code: loginFormData1.code
    }
    proxy.$http.post(url, params, { headers: { "tenant-id": 1 } }).then(v => {
      let { code } = v.data
      let { accessToken } = v.data.data
      let { refreshToken } = v.data.data
      // console.log(code, accessToken)
      if (code == 0) {
        ElMessage.success('登录成功！')
        router.push("/modelTrain/index")
        localStorage.setItem('username', loginFormData1.email!)
        localStorage.setItem('token', accessToken!)
        localStorage.setItem('refreshToken', refreshToken!)
      }
    })
  }

}
/** 创建验证码 */
const createCode = () => {
  // 先清空验证码的输入
  loginFormData.code = ""
  // 获取验证码
  codeUrl.value = ""
  getLoginCodeApi().then((res) => {
    codeUrl.value = res.data
  })
}
const goRegister = () => {
  router.push({ path: "/register" })
}
const gotoFindPage = () => {
  router.push({ path: "/find" })
}

/** 初始化验证码 */
// createCode()
</script>

<template>
  <div class="login-container">
    <ThemeSwitch class="theme-switch" />
    <div class="login-card">
      <div class="title">
        <h1>焊接大数据平台</h1>
        <!-- <img src="@/assets/layouts/logo-text-2.png" /> -->
      </div>
      <div class="content">
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane label="账号密码登录" name="0">
            <el-form ref="loginFormRef" :model="loginFormData" :rules="loginFormRules" @keyup.enter="handleLogin">
              <el-form-item prop="username">
                <el-input v-model.trim="loginFormData.username" placeholder="用户名" type="text" tabindex="1"
                  :prefix-icon="User" size="large" />
              </el-form-item>
              <el-form-item prop="password">
                <el-input v-model.trim="loginFormData.password" placeholder="密码" type="password" tabindex="2"
                  :prefix-icon="Lock" size="large" show-password />
              </el-form-item>

              <!-- <el-form-item prop="code">
            <el-input
              v-model.trim="loginFormData.code"
              placeholder="验证码"
              type="text"
              tabindex="3"
              :prefix-icon="Key"
              maxlength="7"
              size="large"
            >
              <template #append>
                <el-image :src="codeUrl" @click="createCode" draggable="false">
                  <template #placeholder>
                    <el-icon>
                      <Picture />
                    </el-icon>
                  </template>
<template #error>
                    <el-icon>
                      <Loading />
                    </el-icon>
                  </template>
</el-image>
</template>
</el-input>
</el-form-item> -->
              <el-button class="!bg-[#005573]" :loading="loading" type="primary" size="large"
                @click.prevent="handleLogin">登录</el-button>
              <el-form-item class="!m-0 " prop="">
                <!-- <span class="text-[#00afee] text-small cursor-pointer mr-auto" @click="gotoFindPage">找回密码</span>
                <span class="text-[#00afee] text-small cursor-pointer" @click="goRegister">没有账号？点我注册</span> -->
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <!-- <el-tab-pane label="邮箱验证登录" name="1">
            <el-form ref="loginFormRef1" :model="loginFormData1" :rules="loginFormRule1" @keyup.enter="handleLogin">

              <el-form-item prop="email" class="email relative ">
                <el-input v-model.trim="loginFormData1.email" placeholder="请输入邮箱" type="email" tabindex="2"
                  :prefix-icon="Monitor" size="large" />
                <el-button class="!w-21 !h-full" @click="sendEmail" :disabled="sendEmailRef">{{ emailMes }}</el-button>
              </el-form-item>
              <el-form-item prop="code">
                <el-input v-model.trim="loginFormData1.code" autocomplete="off1" placeholder="请输入收到的邮箱验证码" type="text"
                  :prefix-icon="Ticket" size="large" />
              </el-form-item>

              <el-button class="!bg-[#005573]" :loading="loading" type="primary" size="large"
                @click.prevent="handleLogin">登录</el-button>
              <el-form-item class="!m-0 " prop="">
                <span class="text-[#00afee] text-small cursor-pointer mr-auto" @click="gotoFindPage">找回密码</span>
                <span class="text-[#00afee] text-small cursor-pointer" @click="goRegister">没有账号？点我注册</span>
              </el-form-item>
            </el-form>
          </el-tab-pane> -->
        </el-tabs>

      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.email {
  :deep(.el-form-item__content) {
    flex-direction: row;
    flex-wrap: nowrap;
    gap: 5px;
  }
}

.el-form-item {
  &:deep(.el-form-item__content) {
    justify-content: flex-end;
  }
}

.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  min-height: 100%;

  .theme-switch {
    position: fixed;
    top: 5%;
    right: 5%;
    cursor: pointer;
  }

  .login-card {
    width: 480px;
    border-radius: 20px;
    box-shadow: 0 0 10px #dcdfe6;
    background-color: #fff;
    overflow: hidden;

    .title {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 150px;

      img {
        height: 100%;
      }
    }

    .content {
      padding: 20px 50px 50px 50px;

      :deep(.el-input-group__append) {
        padding: 0;
        overflow: hidden;

        .el-image {
          width: 100px;
          height: 40px;
          border-left: 0px;
          user-select: none;
          cursor: pointer;
          text-align: center;
        }
      }

      .el-button {
        width: 100%;
      }
    }
  }
}
</style>
